package com.lagou.util;

import com.lagou.container.StandardContext;
import com.lagou.container.StandardService;
import com.lagou.container.StandardWrapper;
import com.lagou.pojo.Request;
import com.lagou.pojo.Response;
import com.lagou.servlet.HttpServlet;
import com.lagou.servlet.Servlet;

import java.io.InputStream;
import java.net.Socket;
import java.util.Map;

public class RequestProcessor extends Thread{

    private Socket accept;

    private StandardService standardService;

    public RequestProcessor(Socket accept, StandardService standardService){
        this.accept = accept;
        this.standardService = standardService;
    }

    @Override
    public void run() {
        try{
            InputStream inputStream = accept.getInputStream();
            //网络通讯是间断性的，会存在一个问题，可能请求过来了数据没过来
            Request request = new Request(inputStream);
            Response response = new Response(accept.getOutputStream());
            String url = request.getUrl();

            String[] split = url.split("/"); // "","demo1","lagou"
            //拿到context demo1
            Map<String, StandardContext> contextMap = standardService.getHost().getContextMap();
            StandardContext standardContext = contextMap.get("/" + split[1]);
            if(standardContext == null){
                response.outputHtml(request.getUrl());
            } else {
                StandardWrapper standardWrapper = standardContext.getWrapperMap().get("/" + split[2]);
                if(standardWrapper == null){
                    response.outputHtml(request.getUrl());
                } else {
                    String className = standardWrapper.getClassName();
                    HttpServlet httpservlet = (HttpServlet) Class.forName(className).newInstance();
                    httpservlet.service(request, response);
                }
            }

            accept.close();

        } catch (Exception e){
            e.printStackTrace();
        }

    }
}
